package com.aaa.inside.controller;

import com.aaa.entity.base.Commodity;
import com.aaa.entity.base.Locator;
import com.aaa.entity.inside.Inventory;
import com.aaa.entity.inside.InventoryLocator;
import com.aaa.entity.inside.InventoryLocatorDetail;
import com.aaa.entity.inside.InventoryLocatorInit;
import com.aaa.entity.stock.Stock;
import com.aaa.entity.system.User;
import com.aaa.inside.feign.BaseFeign;
import com.aaa.inside.feign.StockFeign;
import com.aaa.inside.feign.SystemFeign;
import com.aaa.inside.service.InventoryLocatorDetailService;
import com.aaa.inside.service.InventoryLocatorInitService;
import com.aaa.inside.service.InventoryLocatorService;
import com.aaa.inside.service.InventoryService;
import com.aaa.inside.util.JwtUtils;
import com.aaa.inside.vo.InputDetail;
import com.aaa.inside.vo.InvenResult;
import com.aaa.vo.R;
import com.alibaba.excel.converters.string.StringErrorConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.awt.util.IdentityArrayList;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author aaa
 * @since 2020-11-30
 */
@RestController
@RequestMapping("/inside/inventory")
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private BaseFeign baseFeign;
    @Autowired
    private InventoryLocatorService inventoryLocatorService;
    @Autowired
    private StockFeign stockFeign;
    @Autowired
    private InventoryLocatorInitService initService;
    @Autowired
    private InventoryLocatorDetailService detailService;
    @Autowired
    private SystemFeign systemFeign;

    Long warehouseid=41L;
    @ApiOperation("盘点管理")
    @PostMapping("addInventory")
    public R addInventory(@RequestBody List<String> list, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        if (list.size()==0){
            return R.error().message("盘点货位不能为空请重新选择");
        }
        /*通过仓库id查出当前仓库中所有的商品编码和名字*/
        List<Map> comList = baseFeign.selectComBarNamByWareId(warehouseid);
        /*盘点管理表的新增*/
        String inventoryno=getInventoryNo();
        Inventory inventory=new Inventory();
        inventory.setInventoryno(inventoryno);
        inventory.setWarehouseid(warehouseid);
        inventory.setCreator(user.getName());
        Date now=new Date();
        inventory.setCreatetime(now);
        boolean save = inventoryService.save(inventory);
        if (save){
            try {/*盘点货位的新增*/
                for(int i=0;i<list.size();i++){
                    Locator locator = baseFeign.selectTarLocByLoCode(list.get(i), warehouseid);
                    InventoryLocator inventoryLocator=new InventoryLocator();
                    inventoryLocator.setInventoryno(inventoryno);
                    inventoryLocator.setLocatorid(locator.getId());
                    inventoryLocator.setLocatorcode(locator.getCode());
                    inventoryLocator.setLocatorname(locator.getName());
                    inventoryLocator.setCreator(user.getName());
                    Date now1=new Date();
                    inventoryLocator.setCreatetime(now1);
                    inventoryLocatorService.save(inventoryLocator);
                }
            }catch (Exception e){
                e.printStackTrace();
                return R.error().message("inventoryLocator货位表插入错误，盘点失败");
            }
            try {
                for (int i=0;i<list.size();i++){
                    List<Stock> stocks = stockFeign.selectStockByLoCodeWareID(list.get(i), warehouseid);
                    if (stocks==null){
                        return R.ok().message("盘点成功").data("inventyno",inventoryno)
                                .data("comList",comList).data("inventoryno",inventoryno);
                        /*弹出录入明细界面操作*/
                    }else {
                        try {
                            for (Stock stock:stocks) {
                            /*先查s_inventory_locator表中的id作为pid*/
                                QueryWrapper<InventoryLocator> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("inventoryno", inventoryno);
                                queryWrapper.eq("locatorcode", stock.getLocatorcode());
                                InventoryLocator one = inventoryLocatorService.getOne(queryWrapper);
                                InventoryLocatorInit init=new InventoryLocatorInit();
                                init.setPid(one.getId());
                                init.setLocatorid(stock.getLocatorid());
                                init.setLocatorcode(stock.getLocatorcode());
                                init.setLocatorname(stock.getLocatorname());
                                init.setCommodityid(stock.getCommodityid());
                                init.setCommoditybar(stock.getCommoditybar());
                                init.setCommodityname(stock.getCommodityname());
                                init.setQty(stock.getCqty());
                                init.setCreator(user.getName());
                                Date now2=new Date();
                                init.setCreatetime(now2);
                                initService.save(init);
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                            return R.error().message("新增初始化错误，盘点失败");
                        }
                    }
                }
                return R.ok().message("盘点成功").data("inventyno",inventoryno)
                        .data("comList",comList).data("inventoryno",inventoryno);
                /*弹出录入明细界面操作*/
            }catch (Exception e){
                e.printStackTrace();
                return R.error().message("新增初始化错误，盘点失败");
            }

        }
        return R.error().message("新增盘点表错误，盘点失败");
    }
    /*盘点明细录入后点击盘点后*/
    @ApiOperation("盘点明细录入")
    @PostMapping("addDetail")
    public R addDetail(@RequestBody InputDetail inputDetail,HttpServletRequest request){
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        /*先查s_inventory_locator表中的id作为pid*/
        QueryWrapper<InventoryLocator> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("inventoryno", inputDetail.getInventoryno());
        queryWrapper.eq("locatorcode", inputDetail.getLocatorcode());
        InventoryLocator one = inventoryLocatorService.getOne(queryWrapper);
        QueryWrapper<InventoryLocatorDetail> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("pid",one.getId());
        queryWrapper1.eq("locatorcode",inputDetail.getLocatorcode());
        queryWrapper1.eq("commoditybar",inputDetail.getCommoditybar());
        InventoryLocatorDetail detail = detailService.getOne(queryWrapper1);
        if (detail==null){
            InventoryLocatorDetail detail1=new InventoryLocatorDetail();
            Commodity commodity = baseFeign.selectComIdNamByWareIdCbar(inputDetail.getCommoditybar(), warehouseid);
            detail1.setPid(one.getId());
            detail1.setLocatorid(one.getLocatorid());
            detail1.setLocatorcode(inputDetail.getLocatorcode());
            detail1.setLocatorname(one.getLocatorname());
            detail1.setCommodityid(commodity.getId());
            detail1.setCommoditybar(inputDetail.getCommoditybar());
            detail1.setCommodityname(commodity.getName());
            detail1.setQty(inputDetail.getQty());
            detail1.setCreator(user.getName());
            Date now3=new Date();
            detail1.setCreatetime(now3);
            detailService.save(detail1);
        }else {
            detail.setQty(detail.getQty()+inputDetail.getQty());
            detailService.updateById(detail);
        }
        QueryWrapper<Inventory> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("inventoryno",inputDetail.getInventoryno());
        Inventory inventory = inventoryService.getOne(queryWrapper2);
        inventory.setState("1");
        inventoryService.updateById(inventory);
        return R.ok().message("录入成功");
    }
    /*点击录入明细根据传来的盘点单号查询所有改单号的明细*/
    @ApiOperation("点击录入明细根据传来的盘点单号查询所有改单号的明细")
    @PostMapping("selectDetailByInvNo/{inventoryno}")
    public R selectDetailByInvNo(@PathVariable String inventoryno){
        List<InventoryLocatorDetail> details = inventoryService.selectDetailByInvNo(inventoryno);
        return R.ok().data("details",details);
    }
    /*通过盘点单号查询盘点货位*/
    @PostMapping("selectLoByInvNo/{inventoryno}")
    public List<InventoryLocator> selectLoByInvNo(@PathVariable String inventoryno){
        List<InventoryLocator> locators = inventoryService.selectLoByInvNo(inventoryno);
        return locators;
    }
    /*点击盘点结束后*/
    @ApiOperation("点击盘点结束后")
    @PostMapping("invOver/{inventoryno}")
    public R invOver(@PathVariable String inventoryno){
        QueryWrapper<Inventory> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("inventoryno",inventoryno);
        Inventory inventory = inventoryService.getOne(queryWrapper);
        inventory.setState("2");
        boolean b = inventoryService.updateById(inventory);
        if (b){
            return R.ok().message("盘点已结束");
        }return R.error();
    }
    /*删除一个盘点记录*/
    @ApiOperation("删除一个盘点记录")
    @PostMapping("deleteInv/{inventoryno}")
    public R deleteInv(@PathVariable String inventoryno){
        QueryWrapper<Inventory> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("inventoryno",inventoryno);
        boolean a = inventoryService.remove(queryWrapper);
        if (a){
        QueryWrapper<InventoryLocator> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("inventoryno",inventoryno);
            List<InventoryLocator> locators = inventoryLocatorService.list(queryWrapper1);
            boolean b = inventoryLocatorService.remove(queryWrapper1);
            if (b){

                try {
                    for (InventoryLocator locator:locators){
                        QueryWrapper<InventoryLocatorInit> initQueryWrapper=new QueryWrapper<>();
                        initQueryWrapper.eq("pid",locator.getId());
                        initService.remove(initQueryWrapper);
                        QueryWrapper<InventoryLocatorDetail> detailQueryWrapper=new QueryWrapper<>();
                        detailQueryWrapper.eq("pid",locator.getId());
                        detailService.remove(detailQueryWrapper);
                    }
                    return R.ok().message("删除成功!");
                } catch (Exception e) {
                    e.printStackTrace();
                    return R.error();
                }
            }else {
                return R.error();
            }
        }return R.error();
    }
    /*查看盘点结果*/
    @ApiOperation("查看盘点结果")
    @PostMapping("invResult/{inventoryno}")
    public R invResult(@PathVariable String inventoryno){
        List<InvenResult> winResults=new ArrayList<InvenResult>();
        List<InvenResult> losResults=new ArrayList<InvenResult>();
        /*通过盘点单号查询所有待盘点货位的id*/
        List<Long> ids=inventoryLocatorService.selectIdsByInvNo(inventoryno);
        for (Long pid:ids){
            List<Long> idss=new ArrayList<>();
            QueryWrapper<InventoryLocatorInit> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("pid",pid);
            List<InventoryLocatorInit> inits = initService.list(queryWrapper);
            if(inits.size()==0){
                QueryWrapper<InventoryLocatorDetail> queryWrapper1=new QueryWrapper<>();
                queryWrapper1.eq("pid",pid);
                List<InventoryLocatorDetail> details=detailService.list(queryWrapper1);
                if (details.size()==0){
                    continue;
                }else {
                    for (InventoryLocatorDetail detail:details){
                        idss.add(detail.getId());
                        InvenResult result=new InvenResult();
                        result.setCommoditybar(detail.getCommoditybar());
                        result.setCommodityname(detail.getCommodityname());
                        result.setLocatorcode(detail.getLocatorcode());
                        result.setQty(detail.getQty());
                        result.setCreator(detail.getCreator());
                        result.setCreatetime(detail.getCreatetime());
                        winResults.add(result);
                    }
                }
            }else {
                for (InventoryLocatorInit init:inits){
                    QueryWrapper<InventoryLocatorDetail> queryWrapper1=new QueryWrapper<>();
                    queryWrapper1.eq("pid",pid);
                    List<InventoryLocatorDetail> details=detailService.list(queryWrapper1);
                    if (details.size()==0){
                        InvenResult result=new InvenResult();
                        result.setCommoditybar(init.getCommoditybar());
                        result.setCommodityname(init.getCommodityname());
                        result.setLocatorcode(init.getLocatorcode());
                        result.setQty(-init.getQty());
                        result.setCreator(init.getCreator());
                        result.setCreatetime(init.getCreatetime());
                        losResults.add(result);
                    }else {int i=0;
                        for (InventoryLocatorDetail detail:details){
                            if (!init.getCommoditybar().equals(detail.getCommoditybar())){
                                    continue;
                            }else {
                                i++;
                                idss.add(detail.getId());
                                if (detail.getQty()-init.getQty()==0){
                                    continue;
                                }else {
                                    InvenResult result=new InvenResult();
                                    result.setCommoditybar(detail.getCommoditybar());
                                    result.setCommodityname(detail.getCommodityname());
                                    result.setLocatorcode(detail.getLocatorcode());
                                    result.setQty(detail.getQty()-init.getQty());
                                    result.setCreator(detail.getCreator());
                                    result.setCreatetime(detail.getCreatetime());
                                    if (detail.getQty()-init.getQty()>0){
                                        winResults.add(result);
                                    }else {
                                        losResults.add(result);
                                    }
                                }
                            }
                        }
                        if (i==0){
                            InvenResult result=new InvenResult();
                            result.setCommoditybar(init.getCommoditybar());
                            result.setCommodityname(init.getCommodityname());
                            result.setLocatorcode(init.getLocatorcode());
                            result.setQty(-init.getQty());
                            result.setCreator(init.getCreator());
                            result.setCreatetime(init.getCreatetime());
                            losResults.add(result);
                        }
                    }
                }
            }
            List<Long> idsss = detailService.selectIdByPid(pid);
            for (Long id:idsss){
                if (!idss.contains(id)){
                    QueryWrapper<InventoryLocatorDetail> queryWrapper1=new QueryWrapper<>();
                    queryWrapper1.eq("id",id);
                    InventoryLocatorDetail detail=detailService.getOne(queryWrapper1);
                    InvenResult result=new InvenResult();
                    result.setCommoditybar(detail.getCommoditybar());
                    result.setCommodityname(detail.getCommodityname());
                    result.setLocatorcode(detail.getLocatorcode());
                    result.setQty(detail.getQty());
                    result.setCreator(detail.getCreator());
                    result.setCreatetime(detail.getCreatetime());
                    winResults.add(result);
                }
            }

        }
        List<InventoryLocatorDetail> details = detailService.selectDetailByIno(inventoryno);
        return R.ok().data("details",details).data("winResults",winResults).data("losResults",losResults);
    }
    /*点击盘点管理查询盘点管理的表数据*/
    @ApiOperation("点击盘点管理查询盘点管理的表数据")
    @PostMapping("searchInv")
    public R selectInv(){
        Long warehouseid=41L;
        List<Inventory> inventories=inventoryService.selectInv(warehouseid);
        return R.ok().data("inventories",inventories);
    }
    /*点击盘点菜单显示所有货位*/
    @ApiOperation("点击盘点菜单显示所有货位")
    @PostMapping("searchLoc/{page}/{limit}")
    public R selectLoc(@PathVariable Integer page,
                       @PathVariable Integer limit,
                       @RequestBody Locator locator){
        return baseFeign.searchLocator(page, limit, locator, warehouseid);

    }


    /*根据时间生成盘点单号*/
    public static String getInventoryNo() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="IN";
        return result+newDate;
    }

}

